

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta name="referrer" content="no-referrer" />
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/apple-touch-icon.png">
  <link rel="icon" href="/img/fyy.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="fyy">
  <meta name="keywords" content="">
  
    <meta name="description" content="NIO 简介在传统的 Java I&#x2F;O 模型（BIO）中，I&#x2F;O 操作是以阻塞的方式进行的，这种阻塞模型在处理多个并发连接时可能会导致性能瓶颈。 Java1.4 版本引入了 NIO 。NIO 弥补了同步阻塞 I&#x2F;O 的不足，它在标准 Java 代码中提供了非阻塞、面向缓冲、基于通道的 I&#x2F;O，可以使用少量的线程来处理多个连接，大大提高了 I&#x2F;O 效">
<meta property="og:type" content="article">
<meta property="og:title" content="NIO核心知识">
<meta property="og:url" content="http://example.com/2021/04/06/IO/Java%20NIO%E6%A0%B8%E5%BF%83%E7%9F%A5%E8%AF%86/index.html">
<meta property="og:site_name" content="fyy-coding">
<meta property="og:description" content="NIO 简介在传统的 Java I&#x2F;O 模型（BIO）中，I&#x2F;O 操作是以阻塞的方式进行的，这种阻塞模型在处理多个并发连接时可能会导致性能瓶颈。 Java1.4 版本引入了 NIO 。NIO 弥补了同步阻塞 I&#x2F;O 的不足，它在标准 Java 代码中提供了非阻塞、面向缓冲、基于通道的 I&#x2F;O，可以使用少量的线程来处理多个连接，大大提高了 I&#x2F;O 效">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="c:\Users\69425\AppData\Roaming\Typora\typora-user-images\image-20231016175543156.png">
<meta property="og:image" content="c:\Users\69425\AppData\Roaming\Typora\typora-user-images\image-20231016162106420.png">
<meta property="og:image" content="c:\Users\69425\AppData\Roaming\Typora\typora-user-images\image-20231016162411413.png">
<meta property="og:image" content="c:\Users\69425\AppData\Roaming\Typora\typora-user-images\image-20231016190019985.png">
<meta property="og:image" content="c:\Users\69425\AppData\Roaming\Typora\typora-user-images\image-20231016190605292.png">
<meta property="article:published_time" content="2021-04-06T04:13:33.000Z">
<meta property="article:modified_time" content="2024-03-18T12:06:04.827Z">
<meta property="article:author" content="fyy">
<meta property="article:tag" content="NIO">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="c:\Users\69425\AppData\Roaming\Typora\typora-user-images\image-20231016175543156.png">
  
  
  
  <title>NIO核心知识 - fyy-coding</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.7","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":null,"google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"ufph8TbmK43d1JfQxLvss4KY-MdYXbMMI","app_key":"96APiPOtZEiCQlv5h3jjZfbC","server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  

  

  
    <!-- Google tag (gtag.js) -->
    <script async>
      if (!Fluid.ctx.dnt) {
        Fluid.utils.createScript("https://www.googletagmanager.com/gtag/js?id=", function() {
          window.dataLayer = window.dataLayer || [];
          function gtag() {
            dataLayer.push(arguments);
          }
          gtag('js', new Date());
          gtag('config', '');
        });
      }
    </script>
  

  

  

  

  
    
  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>fyy-coding</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/" target="_self">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/" target="_self">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/" target="_self">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/" target="_self">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/" target="_self">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="NIO核心知识"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2021-04-06 12:13" pubdate>
          2021年4月6日 中午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          3.4k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          29 分钟
        
      </span>
    

    
    
      
        <span id="leancloud-page-views-container" class="post-meta" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="leancloud-page-views"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">NIO核心知识</h1>
            
            
              <div class="markdown-body">
                
                <h2 id="NIO-简介"><a href="#NIO-简介" class="headerlink" title="NIO 简介"></a>NIO 简介</h2><p>在传统的 Java I&#x2F;O 模型（BIO）中，I&#x2F;O 操作是以阻塞的方式进行的，这种阻塞模型在处理多个并发连接时可能会导致性能瓶颈。</p>
<p>Java1.4 版本引入了 <strong>NIO</strong> 。NIO 弥补了同步阻塞 I&#x2F;O 的不足，它在标准 Java 代码中提供了非阻塞、面向缓冲、基于通道的 I&#x2F;O，可以使用少量的线程来处理多个连接，大大提高了 I&#x2F;O 效率和并发。</p>
<p>⚠️需要注意：使用 NIO 并不一定意味着高性能，它的性能优势主要体现在高并发和高延迟的网络环境下。当连接数较少、并发程度较低或者网络传输速度较快时，NIO 的性能并不一定优于传统的 BIO 。</p>
<h2 id="NIO-核心组件"><a href="#NIO-核心组件" class="headerlink" title="NIO 核心组件"></a>NIO 核心组件</h2><p>NIO 主要包括以下三个核心组件：</p>
<ul>
<li><strong>Buffer（缓冲区）</strong>：NIO 读写数据都是通过缓冲区进行操作的。读操作的时候将 Channel 中的数据填充到 Buffer 中，而写操作时将 Buffer 中的数据写入到 Channel 中。</li>
<li><strong>Channel（通道）</strong>：Channel 是一个双向的、可读可写的数据传输通道，NIO 通过 Channel 来实现数据的输入输出。通道是一个抽象的概念，它可以代表文件、套接字或者其他数据源之间的连接。</li>
<li><strong>Selector（选择器）</strong>：允许一个线程处理多个 Channel，基于事件驱动的 I&#x2F;O 多路复用模型。所有的 Channel 都可以注册到 Selector 上，由 Selector 来分配线程来处理事件。</li>
</ul>
<p>三者的关系</p>
<p><img src="C:\Users\69425\AppData\Roaming\Typora\typora-user-images\image-20231016175543156.png" srcset="/img/loading.gif" lazyload alt="image-20231016175543156"></p>
<h3 id="Buffer（缓冲区）"><a href="#Buffer（缓冲区）" class="headerlink" title="Buffer（缓冲区）"></a>Buffer（缓冲区）</h3><p>在传统的 BIO 中，数据的读写是面向流的， 分为字节流和字符流。</p>
<p>在 Java 1.4 的 NIO 库中，所有数据都是用缓冲区处理的，这是新库和之前的 BIO 的一个重要区别，有点类似于 BIO 中的缓冲流。NIO 在读取数据时，它是直接读到缓冲区中的。在写入数据时，写入到缓冲区中。 使用 NIO 在读写数据时，都是通过缓冲区进行操作。</p>
<p><code>Buffer</code> 的子类如下图所示。其中，最常用的是 <code>ByteBuffer</code>，它可以用来存储和操作字节数据。</p>
<p>Buffer 的子类</p>
<p><img src="C:\Users\69425\AppData\Roaming\Typora\typora-user-images\image-20231016162106420.png" srcset="/img/loading.gif" lazyload alt="image-20231016162106420"></p>
<p>可以将 Buffer 理解为一个数组，<code>IntBuffer</code>、<code>FloatBuffer</code>、<code>CharBuffer</code> 等分别对应 <code>int[]</code>、<code>float[]</code>、<code>char[]</code> 等。</p>
<p>为了更清晰地认识缓冲区，我们来简单看看<code>Buffer</code> 类中定义的四个成员变量：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Buffer</span> &#123;<br>    <span class="hljs-comment">// Invariants: mark &lt;= position &lt;= limit &lt;= capacity</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> <span class="hljs-variable">mark</span> <span class="hljs-operator">=</span> -<span class="hljs-number">1</span>;<br>    <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> <span class="hljs-variable">position</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br>    <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> limit;<br>    <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> capacity;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>这四个成员变量的具体含义如下：</p>
<ol>
<li>容量（<code>capacity</code>）：<code>Buffer</code>可以存储的最大数据量，<code>Buffer</code>创建时设置且不可改变；</li>
<li>界限（<code>limit</code>）：<code>Buffer</code> 中可以读&#x2F;写数据的边界。写模式下，<code>limit</code> 代表最多能写入的数据，一般等于 <code>capacity</code>（可以通过<code>limit(int newLimit)</code>方法设置）；读模式下，<code>limit</code> 等于 Buffer 中实际写入的数据大小（所有位置都可以写，只有写的位置才可以读）。</li>
<li>位置（<code>position</code>）：索引。从写操作模式到读操作模式切换的时候（flip），<code>position</code> 都会归零。</li>
<li>标记（<code>mark</code>）：<code>Buffer</code>允许将位置直接定位到该标记处，这是一个可选属性；</li>
</ol>
<p>并且，上述变量满足如下的关系：<strong>0 &lt;&#x3D; mark &lt;&#x3D; position &lt;&#x3D; limit &lt;&#x3D; capacity</strong> 。</p>
<p>另外，Buffer 有读模式和写模式这两种模式，分别用于从 Buffer 中读取数据或者向 Buffer 中写入数据。Buffer 被创建之后默认是写模式，调用 <code>flip()</code> 可以切换到读模式。如果要再次切换回写模式，可以调用 <code>clear()</code> 或者 <code>compact()</code> 方法。</p>
<p>position 、limit 和 capacity 之前的关系</p>
<p><img src="C:\Users\69425\AppData\Roaming\Typora\typora-user-images\image-20231016162411413.png" srcset="/img/loading.gif" lazyload alt="image-20231016162411413"></p>
<p><code>Buffer</code> 对象不能通过 <code>new</code> 调用构造方法创建对象 ，只能通过静态方法实例化 <code>Buffer</code>。</p>
<p>以 <code>ByteBuffer</code>为例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 分配堆内存</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ByteBuffer <span class="hljs-title function_">allocate</span><span class="hljs-params">(<span class="hljs-type">int</span> capacity)</span>; <br><span class="hljs-comment">// 分配直接内存</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ByteBuffer <span class="hljs-title function_">allocateDirect</span><span class="hljs-params">(<span class="hljs-type">int</span> capacity)</span>; <br></code></pre></td></tr></table></figure>

<p>Buffer 最核心的两个方法：</p>
<ol>
<li><code>get</code> : 读取缓冲区的数据</li>
<li><code>put</code> ：向缓冲区写入数据</li>
</ol>
<p>其他的重要方法：</p>
<ul>
<li><code>flip</code> ：将缓冲区从写模式切换到读模式，它会将 <code>limit</code> 的值设置为当前 <code>position</code> 的值，将 <code>position</code> 的值设置为 0。</li>
<li><code>clear</code>:  清空缓冲区，将缓冲区从读模式切换到写模式，并将 <code>position</code> 的值设置为 0，将 <code>limit</code> 的值设置为 <code>capacity</code> 的值。</li>
</ul>
<p>Buffer 中数据变化的过程：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.nio.*;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">CharBufferDemo</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        <span class="hljs-comment">// 分配一个容量为8的CharBuffer</span><br>        <span class="hljs-type">CharBuffer</span> <span class="hljs-variable">buffer</span> <span class="hljs-operator">=</span> CharBuffer.allocate(<span class="hljs-number">8</span>);<br>        System.out.println(<span class="hljs-string">&quot;初始状态：&quot;</span>); <br>        printState(buffer); <br><br>        <span class="hljs-comment">// 向buffer写入3个字符</span><br>        buffer.put(<span class="hljs-string">&#x27;a&#x27;</span>).put(<span class="hljs-string">&#x27;b&#x27;</span>).put(<span class="hljs-string">&#x27;c&#x27;</span>);<br>        System.out.println(<span class="hljs-string">&quot;写入3个字符后的状态：&quot;</span>);<br>        printState(buffer);<br><br>        <span class="hljs-comment">// 调用flip()方法，准备读取buffer中的数据，将 position 置 0,limit 的置 3</span><br>        buffer.flip();<br>        System.out.println(<span class="hljs-string">&quot;调用flip()方法后的状态：&quot;</span>);<br>        printState(buffer);<br><br>        <span class="hljs-comment">// 读取字符</span><br>        <span class="hljs-keyword">while</span> (buffer.hasRemaining()) &#123; <br>            System.out.print(buffer.get());<br>        &#125;<br><br>        <span class="hljs-comment">// 调用clear()方法，清空缓冲区，将 position 的值置为 0，将 limit 的值置为 capacity 的值</span><br>        buffer.clear();<br>        System.out.println(<span class="hljs-string">&quot;调用clear()方法后的状态：&quot;</span>);<br>        printState(buffer);<br>        <br>    &#125;<br><br>    <span class="hljs-comment">// 打印buffer的capacity、limit、position、mark的位置</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">printState</span><span class="hljs-params">(CharBuffer buffer)</span> &#123;<br>        System.out.print(<span class="hljs-string">&quot;capacity: &quot;</span> + buffer.capacity());<br>        System.out.print(<span class="hljs-string">&quot;, limit: &quot;</span> + buffer.limit());<br>        System.out.print(<span class="hljs-string">&quot;, position: &quot;</span> + buffer.position());<br>        System.out.print(<span class="hljs-string">&quot;, mark 开始读取的字符: &quot;</span> + buffer.mark());<br>        System.out.println(<span class="hljs-string">&quot;\n&quot;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>输出:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs bash">初始状态：<br>capacity: 8, <span class="hljs-built_in">limit</span>: 8, position: 0<br><br>写入3个字符后的状态：<br>capacity: 8, <span class="hljs-built_in">limit</span>: 8, position: 3<br><br>准备读取buffer中的数据！<br><br>调用flip()方法后的状态：<br>capacity: 8, <span class="hljs-built_in">limit</span>: 3, position: 0<br><br>读取到的数据：abc<br><br>调用clear()方法后的状态：<br>capacity: 8, <span class="hljs-built_in">limit</span>: 8, position: 0   <br></code></pre></td></tr></table></figure>



<h3 id="Channel（通道）"><a href="#Channel（通道）" class="headerlink" title="Channel（通道）"></a>Channel（通道）</h3><p>Channel 是一个通道，它建立了与数据源（如文件、网络套接字等）之间的连接。我们可以利用它来读取和写入数据，就像打开了一条自来水管，让数据在 Channel 中自由流动。</p>
<p>BIO 中的流是单向的，分为各种 <code>InputStream</code>（输入流）和 <code>OutputStream</code>（输出流），数据只是在一个方向上传输。通道与流的不同之处在于通道是双向的，它可以用于读、写或者同时用于读写。</p>
<p>Channel 与前面介绍的 Buffer 打交道，读操作的时候将 Channel 中的数据填充到 Buffer 中，而写操作时将 Buffer 中的数据写入到 Channel 中。</p>
<p><img src="C:\Users\69425\AppData\Roaming\Typora\typora-user-images\image-20231016190019985.png" srcset="/img/loading.gif" lazyload alt="image-20231016190019985">Channel 和 Buffer之间的关系</p>
<p>另外，Channel 是全双工的，它可以比流更好地映射底层操作系统的 API。特别是在 UNIX 网络编程模型中，底层操作系统的通道都是全双工的，同时支持读写操作。</p>
<p>Channel子类中最常用的几种类型的通道：</p>
<ul>
<li><p><code>FileChannel</code>：文件访问通道；</p>
</li>
<li><p><code>SocketChannel</code>、<code>ServerSocketChannel</code>：TCP 通信通道；</p>
</li>
<li><p><code>DatagramChannel</code>：UDP 通信通道；</p>
</li>
</ul>
<p>Channel 最核心的两个方法：</p>
<ol>
<li><p><code>read</code> ：读取数据并写入到 Buffer 中。</p>
</li>
<li><p><code>write</code> ：将 Buffer 中的数据写入到 Channel 中。</p>
</li>
</ol>
<p> <code>FileChannel</code> 读取文件数据</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">RandomAccessFile</span> <span class="hljs-variable">reader</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RandomAccessFile</span>(<span class="hljs-string">&quot;/Users/guide/Documents/test_read.in&quot;</span>, <span class="hljs-string">&quot;r&quot;</span>)) <br><span class="hljs-type">FileChannel</span> <span class="hljs-variable">channel</span> <span class="hljs-operator">=</span> reader.getChannel();<br><span class="hljs-type">ByteBuffer</span> <span class="hljs-variable">buffer</span> <span class="hljs-operator">=</span> ByteBuffer.allocate(<span class="hljs-number">1024</span>);<br>channel.read(buffer);<br></code></pre></td></tr></table></figure>



<h3 id="Selector（选择器）"><a href="#Selector（选择器）" class="headerlink" title="Selector（选择器）"></a>Selector（选择器）</h3><p>Selector（选择器） 是 NIO 中的一个关键组件，它允许一个线程处理多个 Channel。Selector 是基于事件驱动的 I&#x2F;O 多路复用模型，主要运作原理是：通过 Selector 注册通道的事件，Selector 会不断地轮询注册在其上的 Channel。当事件发生时，比如：某个 Channel 上面有新的 TCP 连接接入、读和写事件，这个 Channel 就处于就绪状态，会被 Selector 轮询出来。Selector 会将相关的 Channel 加入到就绪集合中。通过 SelectionKey 可以获取就绪 Channel 的集合，然后对这些就绪的 Channel 进行响应的 I&#x2F;O 操作。</p>
<p>Selector 选择器工作示意图</p>
<p><img src="C:\Users\69425\AppData\Roaming\Typora\typora-user-images\image-20231016190605292.png" srcset="/img/loading.gif" lazyload alt="image-20231016190605292"></p>
<p>一个多路复用器 Selector 可以同时轮询多个 Channel，由于 JDK 使用了 <code>epoll()</code> 代替传统的 <code>select</code> 实现，所以它并没有最大连接句柄 <code>1024/2048</code> 的限制。这也就意味着只需要一个线程负责 Selector 的轮询，就可以接入成千上万的客户端。</p>
<p>Selector 可以监听以下四种事件类型：</p>
<ol>
<li><code>SelectionKey.OP_ACCEPT</code>：表示通道接受连接的事件，这通常用于 <code>ServerSocketChannel</code>。</li>
<li><code>SelectionKey.OP_CONNECT</code>：表示通道完成连接的事件，这通常用于 <code>SocketChannel</code>。</li>
<li><code>SelectionKey.OP_READ</code>：表示通道准备好进行读取的事件，即有数据可读。</li>
<li><code>SelectionKey.OP_WRITE</code>：表示通道准备好进行写入的事件，即可以写入数据。</li>
</ol>
<p><code>Selector</code>是抽象类，可以通过调用此类的 <code>open()</code> 静态方法来创建 Selector 实例。Selector 可以同时监控多个 <code>SelectableChannel</code> 的 <code>IO</code> 状况，是非阻塞 <code>IO</code> 的核心。</p>
<p>一个 Selector 实例有三个 <code>SelectionKey</code> 集合：</p>
<ol>
<li>所有的 <code>SelectionKey</code> 集合：代表了注册在该 Selector 上的 <code>Channel</code>，这个集合可以通过 <code>keys()</code> 方法返回。</li>
<li>被选择的 <code>SelectionKey</code> 集合：代表了所有可通过 <code>select()</code> 方法获取的、需要进行 <code>IO</code> 处理的 Channel，这个集合可以通过 <code>selectedKeys()</code> 返回。</li>
<li>被取消的 <code>SelectionKey</code> 集合：代表了所有被取消注册关系的 <code>Channel</code>，在下一次执行 <code>select()</code> 方法时，这些 <code>Channel</code> 对应的 <code>SelectionKey</code> 会被彻底删除，程序通常无须直接访问该集合，也没有暴露访问的方法。</li>
</ol>
<p>如何遍历被选择的 <code>SelectionKey</code> 集合并进行处理：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs java">Set&lt;SelectionKey&gt; selectedKeys = selector.selectedKeys();<br>Iterator&lt;SelectionKey&gt; keyIterator = selectedKeys.iterator();<br><span class="hljs-keyword">while</span> (keyIterator.hasNext()) &#123;<br>    <span class="hljs-type">SelectionKey</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> keyIterator.next();<br>    <span class="hljs-keyword">if</span> (key != <span class="hljs-literal">null</span>) &#123;<br>        <span class="hljs-keyword">if</span> (key.isAcceptable()) &#123;<br>            <span class="hljs-comment">// ServerSocketChannel 接收了一个新连接</span><br>        &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (key.isConnectable()) &#123;<br>            <span class="hljs-comment">// 表示一个新连接建立</span><br>        &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (key.isReadable()) &#123;<br>            <span class="hljs-comment">// Channel 有准备好的数据，可以读取</span><br>        &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (key.isWritable()) &#123;<br>            <span class="hljs-comment">// Channel 有空闲的 Buffer，可以写入数据</span><br>        &#125;<br>    &#125;<br>    keyIterator.remove();<br>&#125;<br></code></pre></td></tr></table></figure>



<p>Selector 还提供了一系列和 <code>select()</code> 相关的方法：</p>
<ul>
<li><p><code>int select()</code>：监控所有注册的 <code>Channel</code>，当它们中间有需要处理的 <code>IO</code> 操作时，将对应的 <code>SelectionKey</code> 加入被选择的 <code>SelectionKey</code> 集合中，该方法返回这些 <code>Channel</code> 的数量。</p>
</li>
<li><p><code>int select(long timeout)</code>：可以设置超时时长的 <code>select()</code> 操作。</p>
</li>
<li><p><code>int selectNow()</code>：执行一个立即返回的 <code>select()</code> 操作，相对于无参数的 <code>select()</code> 方法而言，<strong>该方法不会阻塞线程</strong>。</p>
</li>
<li><p><code>Selector wakeup()</code>：使一个还未返回的 <code>select()</code> 方法立刻返回。</p>
</li>
</ul>
<p>使用 Selector 实现网络读写的简单示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.io.IOException;<br><span class="hljs-keyword">import</span> java.net.InetSocketAddress;<br><span class="hljs-keyword">import</span> java.nio.ByteBuffer;<br><span class="hljs-keyword">import</span> java.nio.channels.SelectionKey;<br><span class="hljs-keyword">import</span> java.nio.channels.Selector;<br><span class="hljs-keyword">import</span> java.nio.channels.ServerSocketChannel;<br><span class="hljs-keyword">import</span> java.nio.channels.SocketChannel;<br><span class="hljs-keyword">import</span> java.util.Iterator;<br><span class="hljs-keyword">import</span> java.util.Set;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">NioSelectorExample</span> &#123;<br><br>  <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>    <span class="hljs-keyword">try</span> &#123;<br>      <span class="hljs-type">ServerSocketChannel</span> <span class="hljs-variable">serverSocketChannel</span> <span class="hljs-operator">=</span> ServerSocketChannel.open();<br>      serverSocketChannel.configureBlocking(<span class="hljs-literal">false</span>);<br>      serverSocketChannel.socket().bind(<span class="hljs-keyword">new</span> <span class="hljs-title class_">InetSocketAddress</span>(<span class="hljs-number">8080</span>));<br><br>      <span class="hljs-type">Selector</span> <span class="hljs-variable">selector</span> <span class="hljs-operator">=</span> Selector.open();<br>      <span class="hljs-comment">// 将 ServerSocketChannel 注册到 Selector 并监听 OP_ACCEPT 事件</span><br>      serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);<br><br>      <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) &#123;<br>        <span class="hljs-type">int</span> <span class="hljs-variable">readyChannels</span> <span class="hljs-operator">=</span> selector.select();<br><br>        <span class="hljs-keyword">if</span> (readyChannels == <span class="hljs-number">0</span>) &#123;<br>          <span class="hljs-keyword">continue</span>;<br>        &#125;<br><br>        Set&lt;SelectionKey&gt; selectedKeys = selector.selectedKeys();<br>        Iterator&lt;SelectionKey&gt; keyIterator = selectedKeys.iterator();<br><br>        <span class="hljs-keyword">while</span> (keyIterator.hasNext()) &#123;<br>          <span class="hljs-type">SelectionKey</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> keyIterator.next();<br><br>          <span class="hljs-keyword">if</span> (key.isAcceptable()) &#123;<br>            <span class="hljs-comment">// 处理连接事件</span><br>            <span class="hljs-type">ServerSocketChannel</span> <span class="hljs-variable">server</span> <span class="hljs-operator">=</span> (ServerSocketChannel) key.channel();<br>            <span class="hljs-type">SocketChannel</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> server.accept();<br>            client.configureBlocking(<span class="hljs-literal">false</span>);<br><br>            <span class="hljs-comment">// 将客户端通道注册到 Selector 并监听 OP_READ 事件</span><br>            client.register(selector, SelectionKey.OP_READ);<br>          &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (key.isReadable()) &#123;<br>            <span class="hljs-comment">// 处理读事件</span><br>            <span class="hljs-type">SocketChannel</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> (SocketChannel) key.channel();<br>            <span class="hljs-type">ByteBuffer</span> <span class="hljs-variable">buffer</span> <span class="hljs-operator">=</span> ByteBuffer.allocate(<span class="hljs-number">1024</span>);<br>            <span class="hljs-type">int</span> <span class="hljs-variable">bytesRead</span> <span class="hljs-operator">=</span> client.read(buffer);<br><br>            <span class="hljs-keyword">if</span> (bytesRead &gt; <span class="hljs-number">0</span>) &#123;<br>              buffer.flip();<br>              System.out.println(<span class="hljs-string">&quot;收到数据：&quot;</span> +<span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(buffer.array(), <span class="hljs-number">0</span>, bytesRead));<br>              <span class="hljs-comment">// 将客户端通道注册到 Selector 并监听 OP_WRITE 事件</span><br>              client.register(selector, SelectionKey.OP_WRITE);<br>            &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (bytesRead &lt; <span class="hljs-number">0</span>) &#123;<br>              <span class="hljs-comment">// 客户端断开连接</span><br>              client.close();<br>            &#125;<br>          &#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (key.isWritable()) &#123;<br>            <span class="hljs-comment">// 处理写事件</span><br>            <span class="hljs-type">SocketChannel</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> (SocketChannel) key.channel();<br>            <span class="hljs-type">ByteBuffer</span> <span class="hljs-variable">buffer</span> <span class="hljs-operator">=</span> ByteBuffer.wrap(<span class="hljs-string">&quot;Hello, Client!&quot;</span>.getBytes());<br>            client.write(buffer);<br><br>            <span class="hljs-comment">// 将客户端通道注册到 Selector 并监听 OP_READ 事件</span><br>            client.register(selector, SelectionKey.OP_READ);<br>          &#125;<br><br>          keyIterator.remove();<br>        &#125;<br>      &#125;<br>    &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;<br>      e.printStackTrace();<br>    &#125;<br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>在示例中，我们创建了一个简单的服务器，监听 8080 端口，使用 Selector 处理连接、读取和写入事件。当接收到客户端的数据时，服务器将读取数据并将其打印到控制台，然后向客户端回复 “Hello, Client!”。</p>
<h2 id="NIO-零拷贝"><a href="#NIO-零拷贝" class="headerlink" title="NIO 零拷贝"></a>NIO 零拷贝</h2><p>零拷贝是提升 IO 操作性能的一个常用手段，像 ActiveMQ、Kafka 、RocketMQ、QMQ、Netty 等顶级开源项目都用到了零拷贝。</p>
<p>零拷贝是指计算机执行 IO 操作时，CPU 不需要将数据从一个存储区域复制到另一个存储区域，从而可以<strong>减少上下文切换以及 CPU 的拷贝时间</strong>。也就是说，零拷贝主要解决操作系统在处理 I&#x2F;O 操作时频繁复制数据的问题。零拷贝的常见实现技术有： <code>mmap+write</code>、<code>sendfile</code>和 <code>sendfile + DMA gather copy</code> 。</p>
<p>下图展示了各种零拷贝技术的对比图：</p>
<table>
<thead>
<tr>
<th></th>
<th>CPU 拷贝</th>
<th>DMA 拷贝</th>
<th>系统调用</th>
<th>上下文切换</th>
</tr>
</thead>
<tbody><tr>
<td>传统方法</td>
<td>2</td>
<td>2</td>
<td>read+write</td>
<td>4</td>
</tr>
<tr>
<td>mmap+write</td>
<td>1</td>
<td>2</td>
<td>mmap+write</td>
<td>4</td>
</tr>
<tr>
<td>sendfile</td>
<td>1</td>
<td>2</td>
<td>sendfile</td>
<td>2</td>
</tr>
<tr>
<td>sendfile + DMA gather copy</td>
<td>0</td>
<td>2</td>
<td>sendfile</td>
<td>2</td>
</tr>
</tbody></table>
<p>可以看出，无论是传统的 I&#x2F;O 方式，还是引入了零拷贝之后，2 次 DMA(Direct Memory Access) 拷贝是都少不了的。因为两次 DMA 都是依赖硬件完成的。零拷贝主要是减少了 CPU 拷贝及上下文的切换。</p>
<p>Java 对零拷贝的支持：</p>
<ul>
<li><code>MappedByteBuffer</code> 是 NIO 基于内存映射（<code>mmap</code>）这种零拷⻉⽅式的提供的⼀种实现，底层实际是调用了 Linux 内核的 <code>mmap</code> 系统调用。它可以将一个文件或者文件的一部分映射到内存中，形成一个虚拟内存文件，这样就可以直接操作内存中的数据，而不需要通过系统调用来读写文件。</li>
<li><code>FileChannel</code> 的<code>transferTo()/transferFrom()</code>是 NIO 基于发送文件（<code>sendfile</code>）这种零拷贝方式的提供的一种实现，底层实际是调用了 Linux 内核的 <code>sendfile</code>系统调用。它可以直接将文件数据从磁盘发送到网络，而不需要经过用户空间的缓冲区。</li>
</ul>
<p>代码示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">loadFileIntoMemory</span><span class="hljs-params">(File xmlFile)</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>  <span class="hljs-type">FileInputStream</span> <span class="hljs-variable">fis</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">FileInputStream</span>(xmlFile);<br>  <span class="hljs-comment">// 创建 FileChannel 对象</span><br>  <span class="hljs-type">FileChannel</span> <span class="hljs-variable">fc</span> <span class="hljs-operator">=</span> fis.getChannel();<br>  <span class="hljs-comment">// FileChannle.map() 将文件映射到直接内存并返回 MappedByteBuffer 对象</span><br>  <span class="hljs-type">MappedByteBuffer</span> <span class="hljs-variable">mmb</span> <span class="hljs-operator">=</span> fc.map(FileChannel.MapMode.READ_ONLY, <span class="hljs-number">0</span>, fc.size());<br>  xmlFileBuffer = <span class="hljs-keyword">new</span> <span class="hljs-title class_">byte</span>[(<span class="hljs-type">int</span>)fc.size()];<br>  mmb.get(xmlFileBuffer);<br>  fis.close();<br>&#125;<br></code></pre></td></tr></table></figure>



<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>NIO 的核心知识点，包括 NIO 的核心组件和零拷贝。</p>
<p>如果我们需要使用 NIO 构建网络程序的话，不建议直接使用原生 NIO，编程复杂且功能性太弱，推荐使用一些成熟的基于 NIO 的网络编程框架比如 Netty。Netty 在 NIO 的基础上进行了一些优化和扩展比如支持多种协议、支持 SSL&#x2F;TLS 等等。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/NIO/" class="category-chain-item">NIO</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/NIO/" class="print-no-link">#NIO</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>NIO核心知识</div>
      <div>http://example.com/2021/04/06/IO/Java NIO核心知识/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>fyy</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2021年4月6日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/04/06/IO/Java%20IO%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" title="IO设计模式">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">IO设计模式</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/04/06/JUC/AQS/" title="AQS">
                        <span class="hidden-mobile">AQS</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"ufph8TbmK43d1JfQxLvss4KY-MdYXbMMI","appKey":"96APiPOtZEiCQlv5h3jjZfbC","path":"window.location.pathname","placeholder":null,"avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="leancloud-site-pv-container" style="display: none">
        总访问量
        <span id="leancloud-site-pv"></span>
        次
      </span>
    
    
      <span id="leancloud-site-uv-container" style="display: none">
        总访客数
        <span id="leancloud-site-uv"></span>
        人
      </span>
    
    

  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.20.1/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script defer src="/js/leancloud.js" ></script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
